<script lang="ts">
export interface ActiveRegionInfo {
  id: number;
  points: [number, number][];
  name: string;
  comment: string;
  begin: number;
  end: number;
  /** 类型，2表示演习区 3表示养殖区 4表示浮标 5表示沉船 6表示井架 7表示海光缆 8表示未爆弹 9表示训练区 */
  type: number;
}
</script>

<script setup lang="ts">
import { ref, watch, onBeforeUnmount, onMounted, reactive } from 'vue';
import { useTaskStore, useTimeRangeStore, useWeatherStore,useUserStore } from '@/store';
import WindSvg from 'common/src/assets/imgs/weather/wind.svg?component';
import CurrentSvg from 'common/src/assets/imgs/weather/current.svg?component';
import WaveSvg from 'common/src/assets/imgs/weather/wave.svg?component';
import PressureSvg from 'common/src/assets/imgs/weather/pressure.svg?component';
import VisibilitySvg from 'common/src/assets/imgs/weather/visibility.svg?component';
import TemperatureSvg from 'common/src/assets/imgs/weather/temperature.svg?component';
import RainSvg from 'common/src/assets/imgs/weather/rain.svg?component';
import IsobarSvg from 'common/src/assets/imgs/weather/isobar.svg?component';
// import CapeSvg from 'common/src/assets/imgs/weather/cape.svg?component';
// import KSvg from 'common/src/assets/imgs/weather/K.svg?component';
import SPSvg from 'common/src/assets/imgs/weather/sp.svg?component';
import DistanceSvg from 'common/src/assets/imgs/weather/distance.svg?component';
import WeatherSelectSvg from 'common/src/assets/imgs/weather/weather-select.svg?component';
import GlobeIcon from 'common/src/assets/imgs/weather/globeIcon.svg?component';
import RegionSvg from 'common/src/assets/imgs/weather/region.svg?component';
import AddRegionSvg from 'common/src/assets/imgs/weather/add-region.svg?component';
import WXMessageSvg from 'common/src/assets/imgs/weather/wx-message.svg?component';
import ToTalCloudSvg from 'common/src/assets/imgs/weather/total_cloud.svg?component';
import LowCloudSvg from 'common/src/assets/imgs/weather/Low_cloud.svg?component';
import { ToolType, WeatherToolType, WeatherType } from 'common/src/utils/weather';
import PointDecoder from './PointDecoder.vue';
import AttitudeDecoder from './AttitudeDecoder.vue';
import ClimaticDecoder from './ClimaticDecoder.vue';
import { closeMeasure, startMeasure } from 'common/src/utils/measureDistance';
import { closeDrawPolygon, startDrawPolygon } from 'common/src/utils/drawPolygon';
import { regionLayerGroups, hideExerciseArea, hideWxMessage, showExerciseArea, showWxMessage, updateExerciseSrc, wxMessageLayerId } from 'common/src/utils/layer';
import RegionEditDialog from './RegionEditDialog.vue';
import { GeoJSONFeature, MapMouseEvent, Marker } from 'mapbox-gl';
import DeleteSvg from 'common/src/assets/imgs/delete.svg?component';
import EditSvg from 'common/src/assets/imgs/edit.svg?component';
import { ElMessage, ElMessageBox } from 'element-plus';
import { deleteRegionFromId } from 'common/src/apis';
import { startDrawRect, closeDrawRect, updateEditingRect } from 'common/src/utils/drawRect';
import WeatherSelectDialog from './WeatherSelectDialog.vue';
import { regionOptions } from 'common/src/utils/special';
import { useMapEventStore, MapTool } from '@/store/map-event';
import {getTaskFactorStatus} from "@/services/data";



const weatherBtns = [
  { value: WeatherType.wind, label: '10m风', icon: WindSvg },
  { value: WeatherType.wind850, label: '850pa风场', icon: WindSvg },
  { value: WeatherType.seawave, label: '浪', icon: WaveSvg },
  { value: WeatherType.seacurrents, label: '流', icon: CurrentSvg },
  { value: WeatherType.precipitation, label: '降水', icon: RainSvg },
  { value: WeatherType.totalCloud, label: '总云', icon: ToTalCloudSvg },
  { value: WeatherType.lowCloud, label: '低云', icon: LowCloudSvg },
  { value: WeatherType.sst, label: '海温', icon: TemperatureSvg },
  { value: WeatherType.pressure, label: '气压', icon: PressureSvg },
  { value: WeatherType.visibility, label: '能见度', icon: VisibilitySvg },
  // { value: WeatherType.cape, label: 'CAPE', icon: CapeSvg },
  // { value: WeatherType.K, label: 'K', icon: KSvg },
];



// 根据后端返回控制各要素是否可用（true=可点击；false=禁用）
const factorEnabledMap = ref<Record<string, boolean>>(() => ({} as Record<string, boolean>)) as unknown as { value: Record<string, boolean> };
// 初始化为全部可用
function initAllFactorsEnabled() {
  const m: Record<string, boolean> = {}
  weatherBtns.forEach(b => { m[String(b.value)] = true })
  factorEnabledMap.value = m
}


// 可选：暴露函数给模板避免 TS 警告
const factorEnabled = (val: string | number) => factorEnabledMap.value[String(val)] !== false

async function fetchFactorShow(taskId: number | string): Promise<Record<string, boolean>> {
  try {
    const data = await getTaskFactorStatus({taskId})

    return (data ?? {}) as Record<string, boolean>
  } catch (e) {
    console.warn('查询失败。', e)
    return {}
  }
}

onMounted(async () => {
  initAllFactorsEnabled()
  regionActionMarker = new Marker({
    element: regionActionElementRef.value,
    anchor: 'left',
  });
  const taskId = (taskStore as any)?.currentTaskId
  if (taskId) {
    const serverMap = await fetchFactorShow(taskId)
    // 合并：以服务端为准，未给出的键默认 true
    const next: Record<string, boolean> = {}
    weatherBtns.forEach(b => {
      const k = String(b.value)
      next[k] = serverMap.hasOwnProperty(k) ? !!serverMap[k] : true
    })
    factorEnabledMap.value = next
  }
});

const weatherStore = useWeatherStore();
const timeRangeStore = useTimeRangeStore();
const taskStore = useTaskStore();
const userStore = useUserStore();
const mapEvent = useMapEventStore();
const pointDecoderRef = ref<InstanceType<typeof PointDecoder> | null>(null);
const attitudeDecoderRef = ref<InstanceType<typeof AttitudeDecoder> | null>(null);
const climaticDecoderRef = ref<InstanceType<typeof ClimaticDecoder> | null>(null);
const toggleClimaticDecoderActive = () => {
  if (taskStore.infoShow.climaticDecoder) {
    taskStore.infoShow.climaticDecoder = false;
    climaticDecoderRef.value?.endDecoder(weatherStore.map as any);
  } else {
    if (distanceActive.value) {
      mapEvent.deactivate(MapTool.measure);
    }
    if (drawRegionFromMap.value) {
      mapEvent.deactivate(MapTool.drawPolygon);
    }
    if (weatherSelectActive.value) {
      mapEvent.deactivate(MapTool.weatherRect);
    }
    if (taskStore.infoShow.pointDecoder) {
      togglePointDecoderActive();
    }
    if (taskStore.infoShow.attitudeDecoder) {
      toggleAttitudeDecoderActive();
    }
    taskStore.showClimaticDecoderInfo();
    climaticDecoderRef.value?.startDecoder(weatherStore.map as any);
  }
};
const regionEditDialogRef = ref<InstanceType<typeof RegionEditDialog> | null>(null);
const weatherSelectDialogRef = ref<InstanceType<typeof WeatherSelectDialog> | null>(null);

// 等压线：间隔设置弹窗
const isobarIntervalVisible = ref(false);
const isobarIntervalStr = ref('');
// 等压线：激活状态来源（默认/自定义），用于高亮对应标签
const isobarActiveMode = ref<'default' | 'custom' | null>(null);
// 等压线：记忆自定义间隔，用于模式切换与图层刷新
const isobarCustomInterval = ref<number | null>(null);
const distanceActive = ref(false);
// 激活的区域类型（2-9）
const activeRegionTypes = ref<number[]>([]);
const weatherSelectActive = ref(false);
const viewActive = ref(false);
const wxMessageActive = ref(false);
const drawRegionFromMap = ref(false);
const drawRegionFromInput = ref(false);
let regionActionMarker: Marker;
/** 是否已添加过区域点击监听 */
let regionClickListener = false;
let regionClickBoundLayers: string[] = [];
const regionActionElementRef = ref<HTMLDivElement>();
const activeRegionInfo = reactive<ActiveRegionInfo>({
  id: 0,
  points: [],
  name: '',
  comment: '',
  begin: 0,
  end: 0,
  type: 2,
});

const weatherSelectFinish = (points: [[number, number], [number, number]]) => {
  weatherSelectDialogRef.value?.showDialog(points);
};

const handleWeatherClick = (weather: string) => {
  const disabledByFactor = factorEnabledMap.value[String(weather)] === false
  if (disabledByFactor || weatherStore.climateLayerActive || weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe') {
    return;
  }
  if (weather === weatherStore.activeWeather) {
    weatherStore.setActiveWeather();
  } else {
    weatherStore.setActiveWeather(weather);
  }
};

// 图标点击：仅负责显隐；若显示，则沿用上次模式（无则默认）
const handleIsobarIconToggle = () => {
  if (weatherStore.climateLayerActive || weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe') return;
  if (weatherStore.isoActive) {
    weatherStore.hideIsobar();
    isobarActiveMode.value = null;
    return;
  }
  // 显示：按上次模式出图；若无记录则用默认
  if (isobarActiveMode.value === 'custom' && isobarCustomInterval.value != null) {
    weatherStore.updateIsobar(isobarCustomInterval.value as any);
    isobarActiveMode.value = 'custom';
  } else {
    weatherStore.updateIsobar();
    isobarActiveMode.value = 'default';
  }
};

// “默认间隔”标签点击：在默认与自定义之间切换到“默认”；
// 仅当当前就是默认(蓝)时才隐藏
const handleIsobarDefaultLabel = () => {
  if (weatherStore.climateLayerActive || weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe') return;
  if (!weatherStore.isoActive) {
    // 未激活 → 直接按默认出图
    weatherStore.updateIsobar();
    isobarActiveMode.value = 'default';
    return;
  }
  // 已激活
  if (isobarActiveMode.value === 'default') {
    // 当前就是默认(蓝) → 切换显隐：隐藏
    weatherStore.hideIsobar();
    isobarActiveMode.value = null;
  } else {
    // 从自定义切换到默认：保留显示，只更新参数
    weatherStore.updateIsobar();
    isobarActiveMode.value = 'default';
  }
};

// “设置间隔”标签点击：若当前就是自定义(蓝)则隐藏；否则弹出输入框，确认后出图
const handleIsobarCustomClick = () => {
  if (weatherStore.climateLayerActive || weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe') return;
  if (weatherStore.isoActive && isobarActiveMode.value === 'custom') {
    weatherStore.hideIsobar();
    isobarActiveMode.value = null;
    return;
  }
  isobarIntervalVisible.value = true;
};

const confirmIsobarInterval = () => {
  const v = Number(isobarIntervalStr.value);
  if (!Number.isFinite(v) || v <= 0) {
    ElMessage.warning('请输入大于 0 的数字');
    return;
  }
  isobarCustomInterval.value = v;
  isobarIntervalVisible.value = false;
  // 出图并标记自定义模式；若已显示则更新，未显示则显示
  weatherStore.updateIsobar(v as any);
  isobarActiveMode.value = 'custom';
};

const togglePointDecoderActive = () => {
  if (taskStore.infoShow.pointDecoder) {
    taskStore.infoShow.pointDecoder = false;
    pointDecoderRef.value?.endDecoder(weatherStore.map as any);
  } else {
    if (distanceActive.value) {
      mapEvent.deactivate(MapTool.measure);
    }
    if (drawRegionFromMap.value) {
      mapEvent.deactivate(MapTool.drawPolygon);
    }
    if (weatherSelectActive.value) {
      mapEvent.deactivate(MapTool.weatherRect);
    }
    if (taskStore.infoShow.attitudeDecoder) {
      toggleAttitudeDecoderActive();
    }
    // close 区划 popup if open
    if (taskStore.infoShow.climaticDecoder) {
      toggleClimaticDecoderActive();
    }
    taskStore.showPointDecoderInfo();
    pointDecoderRef.value?.startDecoder(weatherStore.map as any);
  }
};

const toggleAttitudeDecoderActive = () => {
  if (taskStore.infoShow.attitudeDecoder) {
    taskStore.infoShow.attitudeDecoder = false;
    attitudeDecoderRef.value?.endDecoder(weatherStore.map as any);
  } else {
    if (distanceActive.value) {
      mapEvent.deactivate(MapTool.measure);
    }
    if (drawRegionFromMap.value) {
      mapEvent.deactivate(MapTool.drawPolygon);
    }
    if (weatherSelectActive.value) {
      mapEvent.deactivate(MapTool.weatherRect);
    }
    if (taskStore.infoShow.pointDecoder) {
      togglePointDecoderActive();
    }
    // close 区划 popup if open
    if (taskStore.infoShow.climaticDecoder) {
      toggleClimaticDecoderActive();
    }
    taskStore.showAttitudeDecoderInfo();
    attitudeDecoderRef.value?.startDecoder(weatherStore.map as any);
  }
};

const toggleDistanceActive = () => {
  mapEvent.toggle(MapTool.measure);
};

const toggleWeatherSelectActive = () => {
  mapEvent.toggle(MapTool.weatherRect);
};

const toggleViewActive = () => {
  // 切换 2D/Globe 视角
  switchView();
  // 与 store 同步激活状态
  viewActive.value = weatherStore.mapMode === 'globe';
};

const handleWeatherSelectComplete = () => {
  weatherSelectActive.value = false;
  closeDrawRect();
};

const addFromMapCallback = (points: [number, number][]) => {
  regionEditDialogRef.value?.editRegion({ points });
};

const showAddRegionFromMap = () => {
  mapEvent.toggle(MapTool.drawPolygon);
  if (taskStore.infoShow.pointDecoder) {
    togglePointDecoderActive();
  }
  if (distanceActive.value) {
    mapEvent.deactivate(MapTool.measure);
  }
  if (weatherSelectActive.value) {
    mapEvent.deactivate(MapTool.weatherRect);
  }
  if (taskStore.infoShow.attitudeDecoder) {
    toggleAttitudeDecoderActive();
  }
};
// —— 与 map-event 兼容的代理注册：由 map-event 负责互斥，UI 与交互仍由 util 完成 ——
function registerAllToolsForMapEvent() {
  const map = weatherStore.map as any;
  const mapReady = () => !!weatherStore.map;
  const globalBlocked = () => weatherStore.climateLayerActive || weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe';

  // 测距
  mapEvent.registerTool(MapTool.measure, {
    title: '测距',
    disabled: () => !mapReady() ? '地图未就绪' : weatherStore.climateLayerActive ? '当前模式不可用' : false,
    async start() {
      distanceActive.value = true;
      startMeasure(map);
    },
    async stop() {
      distanceActive.value = false;
      closeMeasure(map);
    }
  });

  // 气象打包（矩形）
  mapEvent.registerTool(MapTool.weatherRect, {
    title: '气象打包',
    disabled: () => !mapReady() ? '地图未就绪' : weatherStore.climateLayerActive ? '当前模式不可用' : false,
    async start() {
      weatherSelectActive.value = true;
      startDrawRect(map, weatherSelectFinish);
    },
    async stop() {
      weatherSelectActive.value = false;
      closeDrawRect();
    }
  });

  // 手动画多边形
  mapEvent.registerTool(MapTool.drawPolygon, {
    title: '新增区域(手动)',
    disabled: () => !mapReady() ? '地图未就绪' : weatherStore.climateLayerActive ? '当前模式不可用' : false,
    async start() {
      drawRegionFromMap.value = true;
      startDrawPolygon(map, addFromMapCallback);
    },
    async stop() {
      drawRegionFromMap.value = false;
      closeDrawPolygon();
      handleRegionEditComplete();
    }
  });
}

// 地图就绪/更换时注册一次，避免在 map=null 时快照
watch(() => weatherStore.map, (m) => {
  if (!m) return;
  registerAllToolsForMapEvent();
}, { immediate: true });

const showAddRegionFromInput = () => {
  drawRegionFromInput.value = true;
  regionEditDialogRef.value?.editRegion({});
};

const handleRegionEditComplete = () => {
  drawRegionFromInput.value = false;
  drawRegionFromMap.value = false;
  regionActionMarker?.remove();
};

const handleEditRegion = () => {
  const { points, id, name, comment, begin, end, type } = activeRegionInfo;
  regionEditDialogRef.value?.editRegion({
    id, name, points, comment, begin, end, type,
  });
};

const handleDeleteRegion = async () => {
  const { id } = activeRegionInfo;
  await ElMessageBox.confirm(`确定删除该区域吗？`, '删除区域', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  });
  try {
    await deleteRegionFromId(id);
    ElMessage({
      type: 'success',
      message: '操作成功',
    });
    regionActionMarker?.remove();
    updateExerciseSrc(weatherStore.map as any, timeRangeStore.start, timeRangeStore.end);
  } catch {
    ElMessage({
      type: 'warning',
      message: '操作失败，请重试',
    });
  }
};

const handleRegionLayerClick = (e: MapMouseEvent & {
  features?: GeoJSONFeature[] | undefined;
}) => {
  const { lat, lng } = e.lngLat;
  const properties = e.features![0].properties as any;
  const { deletable, id, name, begin, end, comment, points, type, time } = properties;
  if (deletable) {
    regionActionMarker?.setLngLat([lng, lat]).addTo(weatherStore.map as any);
    activeRegionInfo.id = id;
    Object.assign(activeRegionInfo, {
      id, name, begin, end, comment, points: JSON.parse(points), type
    } as Partial<ActiveRegionInfo>);
  }
  let info = `入库时间: ${time} 区域说明: ${comment}`;
  taskStore.updateRegionWxMsgInfo(info);
};

const handleWxMessageLayerClick = (e: MapMouseEvent & {
  features?: GeoJSONFeature[] | undefined;
}) => {
  const properties = e.features![0].properties as any;
  const { description, weatherContent, time } = properties;
  let info = `报告时间: ${time} 报告内容: ${description}`;
  if (weatherContent){
    info = `${info} 气象信息: ${weatherContent}`;
  }
  taskStore.updateRegionWxMsgInfo(info);
};

const getRegionFillLayerIdsByTypes = (types: number[]) => {
  const ids: string[] = [];
  types.forEach((t) => {
    const grp = (regionLayerGroups as Record<number, [string, string, string]>)[t];
    if (grp && grp[0]) ids.push(grp[0]);
  });
  return ids;
};

// 统一控制演习/养殖/浮标/…等多类型区域显隐
const setExerciseLayerActive = (show: boolean) => {
  const map = weatherStore.map!;
  if (show) {
    // 展示所选类型的图层
    showExerciseArea(map as any, activeRegionTypes.value);
    // 重新绑定点击层：根据所选类型获取对应 fill layerId 列表
    const layerIds = getRegionFillLayerIdsByTypes(activeRegionTypes.value);
    if (regionClickListener) {
      if (regionClickBoundLayers.length > 0) {
        map.off('click', regionClickBoundLayers as any, handleRegionLayerClick as any);
      }
    }
    if (layerIds.length > 0) {
      map.on('click', layerIds as any, handleRegionLayerClick as any);
      regionClickListener = true;
      regionClickBoundLayers = layerIds;
    }
  } else {
    hideExerciseArea(map as any);
    if (regionClickListener) {
      if (regionClickBoundLayers.length > 0) {
        map.off('click', regionClickBoundLayers as any, handleRegionLayerClick as any);
      }
      regionClickListener = false;
      regionClickBoundLayers = [];
    }
  }
  regionActionMarker?.remove();
};

// 切换单个类型
const toggleRegionType = (type: number) => {
  if (weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe') return;
  const idx = activeRegionTypes.value.indexOf(type);
  if (idx !== -1) {
    activeRegionTypes.value.splice(idx, 1);
  } else {
    activeRegionTypes.value.push(type);
  }
  if (activeRegionTypes.value.length === 0) {
    setExerciseLayerActive(false);
  } else {
    setExerciseLayerActive(true);
  }
};

// 图标点击：全开/全关
const toggleAllRegionActive = () => {
  if (weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe') return;
  taskStore.infoShow.regionWxMsg = false;
  if (activeRegionTypes.value.length > 0) {
    // 关闭全部
    activeRegionTypes.value = [];
    setExerciseLayerActive(false);
  } else {
    // 打开全部（按配置）
    activeRegionTypes.value = regionOptions.map(o => o.value).slice(0,1);
    setExerciseLayerActive(true);
  }
};

const toggleWxMessageLayer = () => {
  if (weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe') {
    return;
  }
  taskStore.infoShow.regionWxMsg = false;
  if (wxMessageActive.value) {
    hideWxMessage(weatherStore.map as any);
    weatherStore.map!.off('click', [wxMessageLayerId], handleWxMessageLayerClick);
  } else {
    showWxMessage(weatherStore.map as any);
    weatherStore.map!.on('click', [wxMessageLayerId], handleWxMessageLayerClick);
  }
  wxMessageActive.value = !wxMessageActive.value;
};

/** 3D视角 */
function switchView() {
  const map = weatherStore.map!;
  const nextMode: '2d' | 'globe' = weatherStore.mapMode === '2d' ? 'globe' : '2d';

  if (nextMode === 'globe') {
    map.setProjection('globe');              // 切到球面
    map.setFog({                             // 可选：更好看的大气层效果
      'horizon-blend': 0.2,
      'space-color': '#000',
      'high-color': '#245CDF'
    });
    // 这里如需隐藏气象图层，可调用你现有的隐藏方法
    // hideWeatherLayers();
  } else {
    map.setProjection('mercator');           // 回到二维
    map.setFog(null);
    // 如果需要恢复气象图层，在此按需恢复
    // showWeatherLayersIfEnabled();
  }

  // 写回 store
  weatherStore.mapMode = nextMode;
}

watch(()=>weatherStore.mapMode,(val)=> {
  console.log(val,'val');
  if(val === 'globe'){
    weatherStore.hideFeatherLayer();
    weatherStore.hideParticleLayer();
    weatherStore.hideWaveDirLayer();
  }
})

watch(() => timeRangeStore.currentTime, () => {
  if (!weatherStore.climateLayerActive) {
    if (weatherStore.activeWeather) {
      weatherStore.updateWeatherLayer(timeRangeStore.currentTime);
    }
    if (weatherStore.isoActive) {
      const interval = isobarActiveMode.value === 'custom' ? isobarCustomInterval.value as any : undefined;
      weatherStore.updateIsobar(interval);
    }
    if (weatherStore.featherActive) {
      weatherStore.updateFeatherLayer();
    }
    if (weatherStore.particleActive) {
      weatherStore.updateParticleLayer();
    }
    if (weatherStore.waveDirActive) {
      weatherStore.updateWaveDirLayer();
    }
  }
});

watch([
  () => timeRangeStore.start,
  () => timeRangeStore.end,
], () => {
  updateExerciseSrc(weatherStore.map as any, timeRangeStore.start, timeRangeStore.end);
});

// 当气候图层或任务阶段一激活时，隐藏所有单项天气图层
watch(
    () => weatherStore.climateLayerActive || weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe',
    (disabled) => {
      if (disabled) {
        // 如果有激活的单项天气，清除它以隐藏图层
        if (weatherStore.activeWeather) {
          weatherStore.setActiveWeather();
        }
        // 如果等压线也激活，则隐藏等压线
        if (weatherStore.isoActive) {
          weatherStore.hideIsobar();
          isobarActiveMode.value = null;
        }
        // Hide exercise layers of any types when disabled
        if (activeRegionTypes.value.length > 0) {
          hideExerciseArea(weatherStore.map as any);
          if (regionClickBoundLayers.length > 0) {
            weatherStore.map!.off('click', regionClickBoundLayers as any, handleRegionLayerClick as any);
          }
          regionClickListener = false;
          regionClickBoundLayers = [];
          activeRegionTypes.value = [];
        }
        // Hide danger message layer
        if (wxMessageActive.value) {
          hideWxMessage(weatherStore.map as any);
          weatherStore.map!.off('click', [wxMessageLayerId], handleWxMessageLayerClick);
          wxMessageActive.value = false;
        }
        // 统一关闭 map-event 工具，避免残留
        mapEvent.deactivateAll();
      }
    }
);

// 同步视角按钮激活态
watch(() => weatherStore.mapMode, (mode) => {
  viewActive.value = mode === 'globe';
}, { immediate: true });

// regionActionMarker 初始化已移至 onMounted 上方

onBeforeUnmount(() => {
  weatherStore.mapMode = '2d';
});

// 监听 userStore.taskPhase 的变化，根据需求关闭区划
watch(() => userStore.taskPhase, (newPhase) => {
  // 当 taskPhase 回到非 1 时，如果“区划”仍激活，则关闭它
  if (newPhase !== 1 && taskStore.infoShow.climaticDecoder) {
    toggleClimaticDecoderActive();
  }
});
</script>

<template>
  <div class="right-container">
    <div class="weather-select">
      <div
          v-for="weather in weatherBtns"
          :key="weather.value"
          :class="['weather-btn', {
            'weather-btn-active': weatherStore.activeWeather === weather.value,
            'weather-btn-disabled': (!factorEnabled(weather.value)) || weatherStore.climateLayerActive || weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe',
          }]"
          @click="() => handleWeatherClick(weather.value)"
      >
        <span class="weather-btn-svg">
          <component :is="weather.icon" />
        </span>
        <span class="weather-btn-label">{{ weather.label }}</span>
      </div>
      <div class="weather-divider" key="weather-divider"></div>
      <div
          :key="WeatherToolType.pressureLine"
          :class="['weather-btn', {
          'weather-btn-active': weatherStore.isoActive,
          'weather-btn-disabled': weatherStore.climateLayerActive || weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe',
        }]"
      >
        <span class="weather-btn-svg weather-btn-iso-svg" @click="() => handleIsobarIconToggle()">
          <IsobarSvg />
        </span>
        <span class="weather-btn-label-list">
          <span class="label-list-items">
            <span
                class="label-item"
                :class="{'label-item-active': weatherStore.isoActive && isobarActiveMode === 'default'}"
                @click="() => handleIsobarDefaultLabel()"
            >默认间隔</span>
            <span
                class="label-item"
                :class="{'label-item-active': weatherStore.isoActive && isobarActiveMode === 'custom'}"
                @click="() => handleIsobarCustomClick()"
            >设置间隔</span>
          </span>
        </span>
      </div>
      <div
          key="exercise-region"
          :class="['weather-btn', {'weather-btn-active': activeRegionTypes.length > 0,'weather-btn-disabled':weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe'}]"
      >
        <span class="weather-btn-svg weather-btn-region-svg" @click="() => toggleAllRegionActive()">
          <RegionSvg />
        </span>
        <span class="weather-btn-label-list">
          <span class="label-list-items">
            <span
                v-for="opt in regionOptions"
                :key="opt.value"
                :class="['label-item', {'label-item-active': activeRegionTypes.includes(opt.value)}]"
                @click="() => toggleRegionType(opt.value)"
            >{{ opt.label }}</span>
          </span>
        </span>
      </div>
      <div
          key="wx-message"
          :class="['weather-btn', {'weather-btn-active': wxMessageActive,'weather-btn-disabled':weatherStore.isTaskPhaseOne || weatherStore.mapMode === 'globe'}]"
          @click="() => toggleWxMessageLayer()"
      >
        <span class="weather-btn-svg weather-btn-wx-msg-svg">
          <WXMessageSvg />
        </span>
        <span class="weather-btn-label">危险报文</span>
      </div>
      <div
          :key="ToolType.singlePoint"
          :class="['weather-btn', {'weather-btn-active': taskStore.infoShow.pointDecoder || taskStore.infoShow.attitudeDecoder || taskStore.infoShow.climaticDecoder}]"
      >
        <span class="weather-btn-svg weather-btn-sp-svg" @click="() => togglePointDecoderActive()">
          <SPSvg />
        </span>
        <span class="weather-btn-label-list">
          <span class="label-list-items">
            <span :class="['label-item', {'label-item-active': taskStore.infoShow.pointDecoder}]" @click="() => togglePointDecoderActive()">气象</span>
            <!--            <span :class="['label-item', {'label-item-active': taskStore.infoShow.attitudeDecoder}]" @click="() => toggleAttitudeDecoderActive()">姿态</span>-->
            <span v-if="userStore.taskPhase === 1"
                  :class="['label-item', {'label-item-active': taskStore.infoShow.climaticDecoder}]"
                  @click="() => toggleClimaticDecoderActive()">区划</span>
          </span>
        </span>
      </div>
      <div
          :key="ToolType.distance"
          :class="['weather-btn', {'weather-btn-active': distanceActive}]"
          @click="() => toggleDistanceActive()"
      >
        <span class="weather-btn-svg weather-btn-distance-svg">
          <DistanceSvg />
        </span>
        <span class="weather-btn-label">测距</span>
      </div>
      <div
          :key="ToolType.weatherRegion"
          :class="['weather-btn', {'weather-btn-active': weatherSelectActive}]"
          @click="() => toggleWeatherSelectActive()"
      >
        <span class="weather-btn-svg weather-btn-weather-pack-svg">
          <WeatherSelectSvg />
        </span>
        <span class="weather-btn-label">气象打包</span>
      </div>
      <div
          key="add-exercise-region"
          :class="['weather-btn', {'weather-btn-active': drawRegionFromMap || drawRegionFromInput}]"
      >
        <span class="weather-btn-svg weather-btn-add-region-svg" @click="() => showAddRegionFromMap()">
          <AddRegionSvg />
        </span>
        <span class="weather-btn-label-list">
          <span class="label-list-items">
            <span :class="['label-item', {'label-item-active': drawRegionFromMap}]" @click="() => showAddRegionFromMap()">手动</span>
            <span :class="['label-item', {'label-item-active': drawRegionFromInput}]" @click="() => showAddRegionFromInput()">经纬度</span>
          </span>
        </span>
      </div>
      <div
          :class="['weather-btn', {'weather-btn-active': viewActive}]"
          @click="() => toggleViewActive()"
      >
        <span class="weather-btn-svg weather-btn-weather-pack-svg">
          <GlobeIcon />
        </span>
        <span class="weather-btn-label">视角</span>
      </div>
    </div>
    <RegionEditDialog ref="regionEditDialogRef" :complete="handleRegionEditComplete" />
    <el-dialog
        v-model="isobarIntervalVisible"
        class="custom-dialog"
        title="请设置间隔"
        width="320px"
        align-center
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <el-input
          v-model.trim="isobarIntervalStr"
          placeholder="输入等压线间隔"
          @keyup.enter="confirmIsobarInterval"
      />
      <template #footer>
        <el-button type="primary" @click="confirmIsobarInterval">确认</el-button>
      </template>
    </el-dialog>
    <div class="region-action" ref="regionActionElementRef">
      <EditSvg @click.stop="() => handleEditRegion()" />
      <DeleteSvg @click.stop="() => handleDeleteRegion()" />
    </div>
  </div>
  <WeatherSelectDialog ref="weatherSelectDialogRef" :complete="handleWeatherSelectComplete" :update="updateEditingRect" />
  <PointDecoder ref="pointDecoderRef" :active="taskStore.infoShow.pointDecoder" />
  <AttitudeDecoder ref="attitudeDecoderRef" :active="taskStore.infoShow.attitudeDecoder" />
  <ClimaticDecoder ref="climaticDecoderRef" :active="taskStore.infoShow.climaticDecoder" />
</template>

<style lang="less" scoped>
:deep(.el-dialog__body) {
  padding:0 20px!important;
}

.right-container {
  position: absolute;
  right: 10px;
  top: 20px;
  display: flex;
  z-index: 10;
  .weather-select {
    width: 40px;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 10px;
    padding-bottom: 10px;
    background: #1E3049;
    box-shadow: 0px 2px 8px 0px rgba(24,57,86,0.44);
    border-radius: 22px;
    opacity: 0.9;
    &>*:not(:last-child) {
      margin-bottom: 10px;
    }
    ///* 新增的约束 */
    //max-height: 60vw;
    //overflow-y: auto;

    ///* 自定义滚动条 */
    //&::-webkit-scrollbar {
    //  width: 6px;
    //}
    //&::-webkit-scrollbar-thumb {
    //  background-color: rgba(12, 149, 247, 0.6);
    //  border-radius: 3px;
    //}
    //&::-webkit-scrollbar-track {
    //  background: transparent; // 去掉白色底色
    //}
  }
  .weather-btn {
    position: relative;
    cursor: pointer;
    &.weather-btn-active,
    &:not(.weather-btn-disabled):hover {
      .weather-btn-svg {
        background-color: #0C95F7;
        :is(svg) {
          fill: #fff;
        }
      }
      .weather-btn-iso-svg {
        background-color: transparent;
        :deep(.iso-background) {
          fill-opacity: 1;
          fill: #0C95F7;
        }
      }
    }
    &:not(.weather-btn-disabled):hover {
      .weather-btn-label,
      .weather-btn-label-list {
        display: block;
      }
    }
    &.weather-btn-disabled {
      cursor: not-allowed;
      :is(svg) {
        fill: #ccc;
      }
    }
    .weather-btn-svg {
      display: flex;
      width: 26px;
      height: 26px;
      border-radius: 50%;
      align-items: center;
      justify-content: center;
    }
    .weather-btn-iso-svg {
      :is(svg) {
        width: 26px;
        height: 26px;
        :deep(.iso-background) {
          fill-opacity: 0.2;
        }
      }
    }
    .weather-btn-wx-msg-svg {
      padding-bottom: 3px;
      :is(svg) {
        width: 16px;
        height: 16px;
      }
    }
    .weather-btn-sp-svg {
      width: 26px;
      height: 26px;
      :is(svg) {
        width: 18px;
        height: 18px;
      }
    }
    .weather-btn-region-svg {
      :is(svg) {
        width: 24px;
        height: 24px;
      }
    }
    .weather-btn-weather-pack-svg {
      :is(svg) {
        width: 22px;
        height: 22px;
      }
    }
    .weather-btn-add-region-svg {
      :is(svg) {
        width: 17px;
        height: 17px;
      }
    }
    :is(svg) {
      width: 20px;
      height: 20px;
      fill: #0C95F7;
    }
    .weather-btn-label {
      display: none;
      position: absolute;
      top: 4px;
      left: -10px;
      transform: translateX(-100%);
      padding: 3px 8px;
      box-shadow: 0px 2px 6px 0px rgba(0,0,0,0.2);
      font-size: 12px;
      color: #0C95F7;
      border-radius: 6px;
      background: #1E3049;
      white-space: nowrap;
    }
    .weather-btn-label-list {
      display: none;
      position: absolute;
      top: 4px;
      left: -5px;
      transform: translateX(-100% + 16px);
      padding-right: 14px;
      height: fit-content;
    }
    .label-list-items {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: #1E3049;
      color: #ccc;
      border-radius: 6px;
      padding: 0 4px;
    }
    .label-item {
      text-align: center;
      font-size: 12px;
      white-space: nowrap;
      padding: 4px 2px;
      border-width: 1px;
      border-color: transparent;
      border-style: solid;
      &:not(:first-child) {
        border-top-color: rgba(255, 255, 255, 0.5);
      }
      &:hover {
        color: #0C95F7;
      }
    }
    .label-item-active {
      color: #0C95F7;
    }
  }
  .weather-divider {
    width: 35px;
    height: 1px;
    background: linear-gradient(90deg, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1), rgba(255, 255, 255, 0));
    opacity: 0.42;
  }
}
</style>

<style lang="less">
.region-action {
  display: none;
  &>* {
    cursor: pointer;
    &:not(:last-child) {
      margin-right: 6px;
    }
  }
  :is(svg) {
    width: 18px;
    height: 18px;
  }
}
.mapboxgl-canvas-container .region-action.mapboxgl-marker {
  display: block;
}
</style>

